package com.bw.interceptor;

import com.alibaba.fastjson.JSON;
import com.bw.common.JwtUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class LoginInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
       //0.  默认拦截所有人
        boolean flag = false;
        // 1. 获取cookie
        Cookie[] cookies = request.getCookies();

        System.out.println("拦截器获取到的cookie：" + JSON.toJSONString(cookies));
        // 2. 从cookie中过滤出令牌
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                String name = cookie.getName();
                if (name.equals("token")){
                    String token = cookie.getValue();
                    flag = JwtUtils.validToken(token);
                }
            }
        }
        // 如果验证令牌不通过
        if (flag == false){
            response.sendRedirect("/loginPage.do");
        }

        // 链式程序， 去执行其他的拦截器
        return HandlerInterceptor.super.preHandle(request, response, handler);
    }
}
